#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "mpi.h"


int main(int argc, char **argv)
{
	int size, rank;

	int * sendbuf,*recvcounts;
	int *recvbuf; 
	int i = 0;
	
	MPI_Init(&argc, &argv);
	
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);

	printf("Size %d, Rank %d\n",size,rank);

	sendbuf = (int *)malloc(sizeof(int) * size);
	
	recvbuf = (int *)malloc(sizeof(int) * size);
	recvcounts = (int *)malloc(sizeof(int) * size);
	for( i = 0; i < size; i++ )
	{
		sendbuf[i] = i + 1;
		recvcounts[i]=1;
	}
	
	if( rank == 0 )
	{
	//	int * list = (int *)malloc(size * sizeof(int));
		printf("REDUCE-SCATTER ROOT BEFORE: recvbuf[0]=%d  recvbuf[1]=%d\n",recvbuf[0],recvbuf[1]);
		fprintf(stderr, "mark\n");
		MPI_Reduce_scatter(sendbuf,recvbuf,recvcounts,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
		printf("REDUCE-scatter ROOT AFTER: recvbuf[0]=%d recvbuf[1]= %d\n",recvbuf[0],recvbuf[1]);
	}
	else 
	{
//		recvbuf = 100;
//		printf("Reduce SCATTERBEFORE: recvbuf[0]=%d recvbuf[1]=%d\n",recvbuf[0],recvbuf[1]);
		MPI_Reduce_scatter(sendbuf,recvbuf,recvcounts,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
		printf("REDUCE-SCATTER AFTER: recvbuf[0]=%d recvbuf[1] = %d\n",recvbuf[0],recvbuf[1]);
	}
	
	
	MPI_Finalize();
	return 0;
}

